/*
 * @Author: 13177709051 3506463075@qq.com
 * @Date: 2024-10-31 00:09:30
 * @LastEditors: 13177709051 3506463075@qq.com
 * @LastEditTime: 2024-10-31 00:12:07
 * @FilePath: /linux28/mythread/test_thread.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE`
 */
#include <iostream>
#include <vector>
#include <cstdio>
#include <unistd.h>
#include "Thread.hpp"
#include "LockGuard.hpp"

using namespace ThreadMoudle;

int tickets = 10000; // 共享资源，造成了数据不一致的问题

void route(ThreadData *td)
{
    while (true)
    {
        LockGuard lockguard(td->_lock); // RAII风格的锁
        if (tickets > 0)
        {
            // 抢票过程
            usleep(1000); // 1ms -> 抢票花费的时间
            printf("who: %s, get a ticket: %d\n", td->_name.c_str(), tickets);
            tickets--;
        }
        else
        {
            break;
        }
    }
}

static int threadnum = 4;

int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, nullptr);

    std::vector<Thread> threads;
    for (int i = 0; i < threadnum; i++)
    {
        std::string name = "thread-" + std::to_string(i + 1);
        ThreadData *td = new ThreadData(name, &mutex);
        threads.emplace_back(name, route, td);
    }

    for (auto &thread : threads)
    {
        thread.Start();
    }

    for (auto &thread : threads)
    {
        thread.Join();
    }

    pthread_mutex_destroy(&mutex);

    // Thread t1("thread-1", route);
    // Thread t2("thread-2", route);
    // Thread t3("thread-3", route);
    // Thread t4("thread-4", route);

    // t1.Start();
    // t2.Start();
    // t3.Start();
    // t4.Start();

    // t1.Join();
    // t2.Join();
    // t3.Join();
    // t4.Join();
}